<template>
  <el-dialog
    v-model="dialogVisible"
    :title="formType == 'create' ? '新建园区房屋建筑信息' : formType == 'update' ? '编辑园区房屋建筑信息' : '园区房屋建筑信息详情'"
    width="1200px"
    append-to-body
  >
    <div class="kuaicenter">
      <div class="kuai"></div>
      <h2>基础信息</h2>
    </div>
    <el-form ref="formRef" v-loading="formLoading" :disabled="disabled" :model="formData" :rules="formRules" label-width="110px">
      <el-row :gutter="24">
        <el-col :span="6">
          <el-form-item label="所在园区" prop="form.parkFoundationInfoId">
            <el-select v-model="formData.form.parkFoundationInfoId" placeholder="请选择所在园区">
              <el-option v-for="item in foundationInfoList" :key="item.id" :label="item.name" :value="item.id"> </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="楼&nbsp;&nbsp;栋&nbsp;&nbsp;号" prop="form.towerNumber">
            <el-input v-model="formData.form.towerNumber" placeholder="请输入楼栋号" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="所在楼层" prop="form.floor">
            <el-input v-model="formData.form.floor" placeholder="请输入所在楼层" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="房&nbsp;&nbsp;间&nbsp;&nbsp;号" prop="form.roomNumber">
            <el-input v-model="formData.form.roomNumber" placeholder="请输入房间号" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="建筑面积(㎡)" prop="form.floorArea">
            <el-input v-model="formData.form.floorArea" placeholder="请输入建筑面积(㎡)" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="房间环境" prop="form.roomEnvironment">
            <el-select v-model="formData.form.roomEnvironment" placeholder="请选择房间环境">
              <el-option v-for="dict in parkr_building_room_environment" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="房间状态" prop="form.roomState">
            <el-select v-model="formData.form.roomState" :disabled="disableRoomState" placeholder="请选择房间状态">
              <el-option v-for="dict in parkbuilingroom_state" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="对&nbsp;&nbsp;接&nbsp;&nbsp;人" prop="form.contactPerson">
            <el-input v-model="formData.form.contactPerson" placeholder="请输入对接人" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="房屋备注" prop="form.remark">
            <el-input v-model="formData.form.remark" placeholder="请输入备注" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="房屋附件" prop="form.attachments">
            <file-upload v-model="formData.form.attachments" placeholder="请输入房屋附件" />
          </el-form-item>
        </el-col>
      </el-row>
      <div v-if="showLeaseInfo">
        <div class="kuaicenter">
          <div class="kuai"></div>
          <h2>租赁信息</h2>
        </div>
        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="承&nbsp;&nbsp;租&nbsp;&nbsp;人" prop="parkerTenantForm.name">
              <el-input v-model="formData.parkerTenantForm.name" placeholder="请输入承租人" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="缴租频次" prop="parkerTenantForm.frentPaymentFrequency">
              <el-select v-model="formData.parkerTenantForm.frentPaymentFrequency" placeholder="请选择缴租频次">
                <el-option v-for="dict in park_frent_payment_frequency" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="租&nbsp;&nbsp;金(元)" prop="parkerTenantForm.rents">
              <el-input v-model="formData.parkerTenantForm.rents" placeholder="请输入租金" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="联系方式" prop="parkerTenantForm.contactInformation">
              <el-input v-model="formData.parkerTenantForm.contactInformation" placeholder="请输入联系方式" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="开始日期" prop="parkerTenantForm.startTime">
              <el-date-picker
                v-model="formData.parkerTenantForm.startTime"
                clearable
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择开始时间"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="结束日期" prop="parkerTenantForm.endTime">
              <el-date-picker
                v-model="formData.parkerTenantForm.endTime"
                clearable
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择结束时间"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="租&nbsp;&nbsp;期(天)" prop="parkerTenantForm.leaseTerm">
              <el-input v-model="formData.parkerTenantForm.leaseTerm" placeholder="自动计算租期" readonly :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="物业费标准" prop="parkerTenantForm.propertyCostStandard">
              <el-input-number :controls="false" v-model="formData.parkerTenantForm.propertyCostStandard" placeholder="请输入物业费标准" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="租赁备注" prop="parkerTenantForm.remark">
              <el-input v-model="formData.parkerTenantForm.remark" placeholder="请输入租赁备注" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="租赁附件" prop="parkerTenantForm.attachments">
              <file-upload v-model="formData.parkerTenantForm.attachments" placeholder="请输入租赁附件" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="退&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;租" prop="parkerTenantForm.surrenderTenancyStatus">
              <el-select v-model="formData.parkerTenantForm.surrenderTenancyStatus" placeholder="请选择退租状态">
                <el-option v-for="dict in park_surrender_tenancy_status" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="退租时间" prop="parkerTenantForm.rentOutTime">
              <el-date-picker
                v-model="formData.parkerTenantForm.rentOutTime"
                clearable
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择结束时间"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <div style="font-size: 10px; padding-top: 10px">
              注意：选择退租后，基础信息中的房间状态变为空置房，租赁信息及收租计划将清空，您可在历史租赁信息查看！
            </div>
          </el-col>
        </el-row>
      </div>
      <template v-else>
        <el-empty description="请将房间状态修改为已出租以添加租赁信息和收租计划" :image-size="200" />
      </template>
      <div v-if="showLeaseInfo">
        <div class="kuaicenter">
          <div class="kuai"></div>
          <h2>收租计划</h2>
        </div>
        <div>
          <div v-if="formData.rentCollectionPlan.length === 0" style="text-align: right">
            <el-button :loading="buttonLoading" type="primary" @click="handlePush()">辅助生成</el-button>
          </div>
          <H2 class="mb-5" style="text-align: center; font-weight: bold">收租计划信息</H2>
          <el-table :data="formData.rentCollectionPlan" style="width: 100%" :show-summary="true" :summary-method="getSummaries">
            <el-table-column type="index" label="序号" width="60" />
            <el-table-column prop="dueDate" label="应收日期">
              <template #default="scope">
                <el-date-picker v-model="scope.row.dueDate" value-format="YYYY-MM-DD" type="date" />
              </template>
            </el-table-column>

            <el-table-column prop="rentReceivable" label="应收租金(元)">
              <template #default="scope">
                <el-input v-model="scope.row.rentReceivable" class="cell-input" />
              </template>
            </el-table-column>
            <el-table-column prop="collect" label="是否收取" width="160">
              <template #default="scope">
                <el-radio-group v-model="scope.row.collect">
                  <el-radio :value="false" size="large">否</el-radio>
                  <el-radio :value="true" size="large">是</el-radio>
                </el-radio-group>
              </template>
            </el-table-column>
            <el-table-column prop="paidInTime" label="实收日期">
              <template #default="scope">
                <el-date-picker v-model="scope.row.paidInTime" value-format="YYYY-MM-DD" type="date" />
              </template>
            </el-table-column>
            <el-table-column width="110" label="操作" align="center" class-name="small-padding fixed-width">
              <template #default="scope">
                <div v-if="disabled">-</div>
                <div v-else>
                  <el-button link type="primary" @click="handlePush(scope.$index)">新增</el-button>
                  <el-button link type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-form>
    <template v-if="!disabled" #footer>
      <div class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">保 存</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts" name="SystemRoleForm" setup>
import {
  getBuilding,
  addBuilding,
  updateBuilding,
  addParkRentCollectionPlan,
  updateParkRentCollectionPlan,
  parkRentCollectionPlanList,
  delParkRentCollectionPlan
} from '@/api/zichanguanli/parkbuilding/index';
import { validateNumber, validateInteger } from '@/utils/formRules';
import { getTenant, addTenant, updateTenant } from '@/api/zichanguanli/parktenant/index';
import { listFoundationInfoList } from '@/api/zichanguanli/foundationInfo';
import { formatDate } from '@/utils/index';
import { generateRentPlan, generateSingleRentPlan } from '@/utils/genRentProject';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const { parkbuilingroom_state, parkr_building_room_environment, park_surrender_tenancy_status, park_frent_payment_frequency } = toRefs<any>(
  proxy?.useDict('parkbuilingroom_state', 'parkr_building_room_environment', 'park_surrender_tenancy_status', 'park_frent_payment_frequency')
);

console.log('?? ~ parkbuilingroom_state:', parkbuilingroom_state.value);
console.log('?? ~ parkr_building_room_environment:', parkr_building_room_environment.value);
console.log('?? ~ park_surrender_tenancy_status:', park_surrender_tenancy_status.value);
console.log('?? ~ park_frent_payment_frequency:', park_frent_payment_frequency.value);

const disabled: any = ref(false); // 表单是否禁用
const buttonLoading = ref(false); // 按钮的 loading
const dialogVisible = ref(false); // 弹窗的是否展示
const formLoading = ref(false); // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref(''); // 表单的类型：create - 新增；update - 修改
const disableRoomState = ref(false); // 是否禁用房间状态

const formData: any = ref({
  form: {
    parkFoundationInfoId: undefined,
    towerNumber: undefined,
    floor: undefined,
    roomNumber: undefined,
    floorArea: undefined,
    roomEnvironment: undefined,
    roomState: undefined,
    contactPerson: undefined,
    remark: undefined,
    attachments: undefined
  },
  parkerTenantForm: {
    name: undefined,
    frentPaymentFrequency: undefined,
    rents: undefined,
    contactInformation: undefined,
    startTime: undefined,
    endTime: undefined,
    leaseTerm: undefined,
    propertyCostStandard: undefined,
    remark: undefined,
    attachments: undefined,
    surrenderTenancyStatus: undefined,
    rentOutTime: undefined
  },
  rentCollectionPlan: []
});
const formRules = reactive({
  'form.parkFoundationInfoId': [{ required: true, message: '所在园区不能为空', trigger: 'blur' }],
  'form.towerNumber': [{ required: true, message: '楼栋号不能为空', trigger: 'blur' }],
  'form.floor': [
    { required: true, message: '所在楼层不能为空', trigger: 'blur' },
    { validator: validateInteger, trigger: ['change', 'blur'] }
  ],
  'form.roomNumber': [{ required: true, message: '房间号不能为空', trigger: 'blur' }],
  'form.floorArea': [
    { required: true, message: '建筑面积(㎡)不能为空', trigger: 'blur' },
    { validator: validateNumber, trigger: ['change', 'blur'] }
  ],
  'form.roomEnvironment': [{ required: true, message: '房间环境不能为空', trigger: 'change' }],
  'form.roomState': [{ required: true, message: '房间状态不能为空', trigger: 'change' }],
  'form.contactPerson': [{ required: true, message: '对接人不能为空', trigger: 'change' }],
  'parkerTenantForm.name': [{ required: true, message: '承租人不能为空', trigger: 'blur' }],
  'parkerTenantForm.frentPaymentFrequency': [{ required: true, message: '缴租频次不能为空', trigger: 'change' }],
  'parkerTenantForm.contactInformation': [{ pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }],
  'parkerTenantForm.rents': [
    { required: true, message: '租金不能为空', trigger: 'blur' },
    { validator: validateNumber, trigger: ['change', 'blur'] }
  ],
  'parkerTenantForm.startTime': [{ required: true, message: '开始时间不能为空', trigger: 'blur' }],
  'parkerTenantForm.endTime': [{ required: true, message: '结束时间不能为空', trigger: 'blur' }],
  'parkerTenantForm.leaseTerm': [{ validator: validateInteger, trigger: ['change', 'blur'] }]
});
const formRef = ref(); // 表单 Ref

const handlePush = (index?: number) => {
  if (index === undefined) {
    const tenant = formData.value.parkerTenantForm;
    if (!tenant.name) {
      ElMessage({ message: '承租人信息为空不能生成收租计划', type: 'error' });
      return;
    }

    // 检查必要字段
    if (!tenant.frentPaymentFrequency || !tenant.rents || !tenant.startTime || !tenant.endTime) {
      ElMessage({ message: '请完善租赁信息（缴租频次、租金、开始时间、结束时间）', type: 'error' });
      return;
    }

    // 生成收租计划，transform设为false表示不转换租金单位
    const plans = generateRentPlan({
      frequencyOfRentPayments: tenant.frentPaymentFrequency,
      rents: tenant.rents,
      startTime: tenant.startTime,
      endTime: tenant.endTime,
      transform: false
    });

    formData.value.rentCollectionPlan = plans;
  } else {
    // 在指定位置插入一条新的收租计划
    const newPlan = generateSingleRentPlan();
    formData.value.rentCollectionPlan.splice(index + 1, 0, newPlan);
  }
};

const foundationInfoList: any = ref([]); // 园区基础信息列表
/** 查询园区基础信息列表 */
const getParkList = async () => {
  formLoading.value = true;
  const res = await listFoundationInfoList();
  foundationInfoList.value = res.rows;
  console.log('?? ~ getParkList ~ foundationInfoList.value:', foundationInfoList.value);
  formLoading.value = false;
};

const handleDelete = async (index: number, row: any) => {
  if (row.id) {
    await delParkRentCollectionPlan(row.id);
    formData.value.rentCollectionPlan.splice(index, 1);
  } else {
    formData.value.rentCollectionPlan.splice(index, 1);
  }
};

/** 打开弹窗 */
const open = async (type: string, parkBuildingId?: number | string, parkRentId?: number | string) => {
  console.log('?? ~ open ~ id:', parkBuildingId);
  getParkList();
  dialogVisible.value = true;
  formType.value = type;
  disabled.value = false;
  resetForm();
  // 修改时，设置数据
  if (type === 'detail') {
    disabled.value = true;
  }
  if (parkBuildingId) {
    formLoading.value = true;
    try {
      const params = {
        parkBuildingId,
        parkRentId: parkRentId,
        isHistory: false
      };
      const res = await getBuilding(params);
      const datas = res.data;
      disableRoomState.value = datas.parkBuildingBo.roomState === 'leased';
      console.log('?? ~ open ~ disableRoomState.value:', disableRoomState.value);
      formData.value.form = datas.parkBuildingBo;
      formData.value.parkerTenantForm = datas.parkTenantBo || {};
      formData.value.rentCollectionPlan = datas.parkRentCollectionPlanBo || [];
    } finally {
      formLoading.value = false;
    }
  }
};

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    form: {
      parkFoundationInfoId: undefined,
      towerNumber: undefined,
      floor: undefined,
      roomNumber: undefined,
      floorArea: undefined,
      roomEnvironment: undefined,
      roomState: 'in_idle',
      contactPerson: undefined,
      remark: undefined,
      attachments: undefined
    },
    parkerTenantForm: {
      name: undefined,
      frentPaymentFrequency: undefined,
      rents: undefined,
      contactInformation: undefined,
      startTime: undefined,
      endTime: undefined,
      leaseTerm: undefined,
      propertyCostStandard: undefined,
      remark: undefined,
      attachments: undefined,
      surrenderTenancyStatus: undefined,
      rentOutTime: undefined
    },
    rentCollectionPlan: []
  };
  formRef.value?.resetFields();
  disableRoomState.value = false;
};

const showLeaseInfo = computed(() => {
  return formData.value.form.roomState === 'leased';
});

defineExpose({ open }); // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']); // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  const valid = await formRef.value.validate();
  if (!valid) return;
  // 提交请求
  formLoading.value = true;
  try {
    let type = '';
    if (formType.value === 'create') {
      type = 'create';
      const datas = {
        parkBuildingBo: formData.value.form,
        parkTenantBo: formData.value.parkerTenantForm,
        parkRentCollectionPlanBo: formData.value.rentCollectionPlan
      };
      await addBuilding(datas);
      buttonLoading.value = false;
    } else {
      type = 'update';
      const datas = {
        parkBuildingBo: formData.value.form,
        parkTenantBo: formData.value.parkerTenantForm,
        parkRentCollectionPlanBo: formData.value.rentCollectionPlan
      };
      await updateBuilding(datas);
    }
    dialogVisible.value = false;
    // 发送操作成功的事件
    emit('success', type);
  } finally {
    formLoading.value = false;
  }
};

// 修改 watch 来计算天数而不是年份
watch([() => formData.value.parkerTenantForm.startTime, () => formData.value.parkerTenantForm.endTime], ([newStartTime, newEndTime]) => {
  if (newStartTime && newEndTime) {
    const startDate = new Date(newStartTime);
    const endDate = new Date(newEndTime);

    // 确保结束时间大于开始时间
    if (endDate <= startDate) {
      formData.value.parkerTenantForm.endTime = null;
      formData.value.parkerTenantForm.leaseTerm = undefined;
      ElMessage.warning('结束时间必须大于开始时间');
      return;
    }

    // 计算天数差值
    const diffTime = Math.abs(endDate - startDate);
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));

    // 直接设置天数
    formData.value.parkerTenantForm.leaseTerm = diffDays;
  } else {
    formData.value.parkerTenantForm.leaseTerm = undefined;
  }
});

// 添加对房间状态的监听
watch(
  () => formData.value.form.roomState,
  (newState) => {
    if (newState !== 'leased' && formType.value != 'history' && formType.value != 'detail') {
      // 如果切换到非已出租状态，清空租赁信息和收租计划
      formData.value.parkerTenantForm = {
        name: undefined,
        frentPaymentFrequency: undefined,
        rents: undefined,
        contactInformation: undefined,
        startTime: undefined,
        endTime: undefined,
        leaseTerm: undefined,
        propertyCostStandard: undefined,
        remark: undefined,
        attachments: undefined,
        surrenderTenancyStatus: undefined,
        rentOutTime: undefined
      };
      formData.value.rentCollectionPlan = [];
    }
    if (newState === 'leased' && formType.value != 'history' && formType.value != 'detail') {
      // 当状态为已租赁时，设置退租状态为在租
      formData.value.parkerTenantForm.surrenderTenancyStatus = 'under_rent';
    }
  }
);

// 1. 添加合计行计算方法
const getSummaries = (param: any) => {
  const { columns, data } = param;
  const sums: any[] = [];
  columns.forEach((column: any, index: number) => {
    if (index === 0) {
      sums[index] = '合计';
      return;
    }
    if (index === 2) {
      // 应收租金列的索引
      const values = data.map((item: any) => Number(item.rentReceivable) || 0);
      sums[index] = values.reduce((prev: number, curr: number) => {
        return prev + curr;
      }, 0);
      // 格式化数字，保留2位小数
      sums[index] = sums[index].toFixed(2);
    } else {
      sums[index] = '';
    }
  });
  return sums;
};
</script>
